"""
迭代器与生成器
https://www.bilibili.com/video/BV18R4y1t7Hg?from=search&seid=15610753137937189430&spm_id_from=333.337.0.0
"""

print("==========迭代器==========")

list1 = [1, 2, 3]
a = iter(list1)
print(type(a))
print(a.__next__())
print(next(a))
print(next(a))
print('------------------------------')


# 创建一个返回数字的迭代器，初始值为 1，逐步递增 1
class MyNumbers:
    def __iter__(self):
        self.a = 1
        return self

    def __next__(self):
        x = self.a
        self.a += 1
        return x


myClass = MyNumbers()
myiter = iter(myClass)

print(next(myiter))
print(next(myiter))
print(next(myiter))

print('------------------------------')


# 在 6 次迭代后停止执行：
class MyNumbers2:
    def __iter__(self):
        self.a = 1
        return self

    def __next__(self):
        if self.a <= 6:
            x = self.a
            self.a += 1
            return x
        else:
            raise StopIteration


myClass2 = MyNumbers2()
myiter2 = iter(myClass2)

for x in myiter2:
    print(x)

print("==========生成器==========")
